<?php

namespace Post\Controller;

use Common\Controller\ApiController;
use Util\ModelUtils;
//use Util\Tree;
use Common\Model\ModelException;
use Util\StringUtils;
use Payment\Client\Charge;
//use Biz\Baidu;
use Ruben\Yxyun\Yxim;
use Carbon\Carbon;

class PostController extends ApiController {

    protected $Model = NULL;
    protected $faccids = [];
    protected $user_field = ['user_id', 'face', 'nickname', 'sex', 'token','intro'];

    public function _initialize() {
        parent::_initialize();
        $this->Model = D(CONTROLLER_NAME);
    }

    //动态首页
    public function search() {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $latest = filter($input['latest'], 0);
        $type = filter($input['type'], 'latest');
        $keyword = filter($input['keyword'], '');
        $ptype = filter($input['ptype'], 'all');
        $tag = filter($input['tag_id'], null);
        $lat = filter($input['lat'], '');
        $lng = filter($input['lng'], '');
        $uid = $this->user['id'];
//        $where = [];
        if ($page == 1) {
            // 添加统计量
            D('Statistical')->addCount('posts_count' . '_' . $type);
            // 不修改前端前提下避免重复数据
            S('post_page_lock_' . $this->token, time(), 60);
        } else {
            $lastest = S('post_page_lock_' . $this->token);
            // 不能完全避免
            if ($lastest)
                $where['create_time'] = ['elt', $lastest];
        }

        if ($tag) {
            $where['tag_id'] = $tag;
        }
        if ($keyword !== '') {
            $where['details'] = ['like', "%{$keyword}%"];
        }
        if ($ptype == 'video') {
            $where['type'] = 2;
        } elseif ($ptype == 'text') {
            $where['type'] = 1;
        }
        if (isset($input['user_id'])) {
            $where['user_id'] = $input['user_id'];
        }
        $order = [];
        $order['create_time'] = 'desc';

        D('Post')->autofill();

        //不显示屏蔽用户的动态
//        $shieldModel = D('shield_user_post');
//        $shield_uid = $shieldModel->where(['user_id' => $uid])->getField('to_user_id', true);
//        if ($shield_uid) {
//            $where['user_id'] = ['not in', $shield_uid];
//        }

        $where = $this->whow_show();
        $count = D('Post')->scope('valid')->where($where)->count();
        $posts = D('Post')
                ->scope('valid')
                ->where($where)
                ->order($order)
                ->page($page, $perPage)
                ->select();
        ModelUtils::belongsTo($posts, ['foreignKey' => 'user_id', 'relation' => 'Account/Users', 'refKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
//        ModelUtils::belongsTo($posts, ['foreignKey' => 'tag_id', 'relation' => 'PostTag', 'name' => 'tag']);
        $posts = transform('Post', 'index', $posts);
        $uids = D('UserFavorite')->where(['user_id' => $uid])->getField('to_user_id', true);

        foreach ($posts as $key => &$value) {
            $value['is_favorite'] = 0;
            if (!empty($uids)) {
                if (in_array($value['author']['user_id'], $uids) || $value['author']['user_id'] == $uid) {
                    $value['is_favorite'] = 1;
                }
            }
        }

        $pagination = pagination($count, $perPage, $page);
        $this->response($posts, $pagination);
    }

    //不可见：所有人可见，好友可见
    protected function whow_show() {
        
        $uid = $this->user['id'];
        $w = "(( accid={$uid} and type=3 and delete_time=0 and relation_type=0) or (faccid={$uid} and type=3 and delete_time=0 and relation_type=0))";
        $UserFriends = D('UserFriends')->where($w)->select();
        $faccids = [];
        array_map(function($value) use (&$faccids,$uid){
            if($value['accid']!=$uid ){
               $faccids[] = $value['accid'];
            }
            if($value['faccid']!=$uid){
               $faccids[] = $value['faccid'];
            }
            
        },$UserFriends);
        $where = "( who_show in (0,2))";
        if (!empty($faccids)) {
            $this->faccids = $faccids;
            $faccids = array_unique($faccids);
            $who_show_is = $faccids;
            $who_show_is[] = $uid;
            $faccids_str = implode(',', $faccids);
            $who_show_is_str = implode(',', $who_show_is);
            $where = "( who_show=0 or (who_show=1 and user_id in ({$who_show_is_str})) or (who_show=2 and user_id not in ({$faccids_str})))";
        }

        return $where;
    }

    //首页关注
    public function follow() {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $latest = filter($input['latest'], 0);
        $type = filter($input['type'], 'latest');
        $keyword = filter($input['keyword'], '');
        $ptype = filter($input['ptype'], 'all');
        $tag = filter($input['tag_id'], null);
        $lat = filter($input['lat'], '');
        $lng = filter($input['lng'], '');
        $uid = $this->user['id'];
        $where = [];
        
        D('Post')->autofill();

        //关注和好友
        $UserFavoriteM = D('UserFavorite');
        $count = 0;
        // $str = "(uf.accid=p.user_id and uf.faccid={$uid} and uf.type=3 and uf.delete_time=0 and uf.relation_type =0) or (uf.faccid=p.user_id and uf.accid={$uid} and uf.type=3 and uf.delete_time=0 and uf.relation_type =0)";

        $UserFriendsM = D('UserFriends');
        $where1 = "((accid={$uid} and type=3 and delete_time=0 and relation_type=0) or (faccid={$uid} and type=3 and delete_time=0 and relation_type=0))";
        $myfriend = S('myfriend_' . $uid);
        if (empty($myfriend)) {
            $myfriend = D('UserFriends')->where($where1)->select();
            if (!empty($myfriend)) {
                S('myfriend_' . $uid, $myfriend, 30);
            }
        }
        \Think\Log::record(json_encode($myfriend), '----myfriend----', TRUE);
        $faccids = [];
        if (!empty($myfriend)) {
            array_map(function($value) use (&$faccids) {
                if ($value['accid'] != $this->user['id']) {
                    $faccids[] = $value['accid'];
                }
                if ($value['faccid'] != $this->user['id']) {
                    $faccids[] = $value['faccid'];
                }
            }, $myfriend);
        }
        $whe = '';
        if(!empty($faccids)){
        	$faccids_str = implode(',', $faccids);
        	$whe = "and (p.who_show = 0 or (p.user_id in ({$faccids_str}) and p.who_show=1) or (p.user_id not in ({$faccids_str}) and p.who_show!=2))";
        }
        
        if(empty($faccids)){
			$whe = "and (p.who_show !=1)";
        }
        
        
        
//        $where['u.user_id'] = $uid;
        $count = $UserFavoriteM
                ->table('__USER_FAVORITE__ as u')
                ->join("__POST__ as p on u.to_user_id=p.user_id and u.user_id={$uid} and p.delete_time=0  and p.audit=1 and p.is_transed='Y' {$whe}")
                // ->join("__USER_FRIENDS__ as uf on (({$str})  and p.who_show<2)",'left')
//                ->where($where)
                ->count();
        $posts = [];
        if ($count>0) {
        	
            $posts = $UserFavoriteM
                    ->table('__USER_FAVORITE__ as u')
                    ->join("__POST__ as p on u.to_user_id=p.user_id and u.user_id={$uid} and p.delete_time=0  and p.audit=1 and p.is_transed='Y' {$whe}")
                    // ->join("__USER_FRIENDS__ as uf on (({$str})  and p.who_show<2)",'left')
                    ->where($where)
                    ->order('p.create_time desc')
                    ->page($page, $perPage)
                    ->select();
          ModelUtils::belongsTo($posts, ['foreignKey' => 'user_id', 'relation' => 'Account/Users', 'refKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
          $posts = D('Post')->_after_select($posts);
         
          $posts = transform('Post', 'index', $posts);
        }
        $pagination = pagination($count, $perPage, $page);
        $this->response($posts, $pagination);
    }
    
    public function getTags() {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $keyword = filter($input['keyword'], '');
        if ($keyword) {
            if (mb_strlen($input['keyword']) > 6) {
                $this->errorResponse(20004, '话题最长6个字');
            }
        }

        $where = [];
        if ($keyword) {
            $where['name'] = ['like', "%{$keyword}%"];
        }
        $count = D('PostTag')->where($where)->count();
        $tags = D('PostTag')
                ->where($where)
                ->page($page, $perPage)
                ->order('is_hot desc')
                ->select();
        $tags = transform('PostTag', 'listview', $tags);
        $pagination = pagination($count, $perPage, $page);
        $this->response($tags, $pagination);
    }

    public function reward($id) {
        $input = $this->request();
        $user = D('Users')->find($this->user['id']);
        $log = D('PaymentLog')->where(['uid' => $this->user['id'], 'order_ids' => $id, 'status' => 'paid', 'type' => 'tips'])->find();
        if ($log)
            $this->errorResponse(80011);
        $amount = filter($input['amount'], 0);
        $post = D('Post')->find($id);
        $channel = $input['channel'];
        if ($amount < 0) {
            $this->errorResponse(10017);
        }
        if ($post['user_id'] === $user['user_id']) {
            $this->errorResponse(10018);
        }
        $author = D('Users')->find($post['user_id']);
        $payOrderNo = 'TIPS' . date('YmdHis') . StringUtils::randString(4, 1);
        $remark = "支付（{$author['nickname']}的动态：" . mb_substr($post['details'], 0, 20) . "  ）" . round($amount / 100, 2) . "元作为奖励";
        D('PaymentLog')->add([
            'uid' => $user['user_id'],
            'amount' => $amount,
            'channel' => $channel,
            'type' => 'tips',
            'create_time' => time(),
            'status' => 'unpaid',
            'payment_no' => $payOrderNo,
            'order_ids' => $id,
            'remark' => $remark,
        ]);

        $payData = [
            'body' => '打赏',
            'subject' => '打赏',
            'order_no' => $payOrderNo,
            'timeout_express' => time() + 600, // 表示必须 600s 内付款
            'amount' => $amount / 100, // 单位为元 ,最小为0.01
            'return_param' => '',
            'client_ip' => get_client_ip(),
            'goods_type' => '0', // 0 虚拟 1 实体
            'store_id' => '',
            'qr_mod' => '',
        ];

        switch ($channel) {
            case 'ali_web':
            case 'ali_wap':
                try {
                    $config = C('sdk.alipay');
                    $redirectUrl = Charge::run($channel, $config, $payData);
                    $this->createdResponse(['redirect_url' => $redirectUrl]);
                } catch (PayException $e) {
                    $this->errorResponse(10015, $e->getMessage());
                }
                break;
            case 'ali_app':
                $config = C('sdk.alipay');
                try {
                    $ret = Charge::run($channel, $config, $payData);
                    $this->createdResponse(['param_str' => $ret, 'channel' => 'alipay']);
                } catch (PayException $e) {
                    $this->errorResponse(10015, $e->getMessage());
                }
                break;
            case 'wx_app':
                $config = C('sdk.wxpay');
                try {
                    $ret = Charge::run($channel, $config, $payData);
                    $ret['packages'] = $ret['package'];
                    $this->createdResponse(['param_obj' => $ret, 'channel' => 'wxpay']);
                } catch (PayException $e) {
                    $this->errorResponse(10015, $e->getMessage());
                }
                break;
            case 'wx_wap':
                $config = C('sdk.wxpay');
                try {
                    $ret = Charge::run($channel, $config, $payData);
                    $this->createdResponse(['redirect_url' => $ret, 'channel' => 'wxpay']);
                } catch (PayException $e) {
                    $this->errorResponse(10015, $e->getMessage());
                }
                break;
            case 'wx_qr':
                $config = C('sdk.wxpay');
                try {
                    $payData['product_id'] = 'reward01';
                    $ret = Charge::run($channel, $config, $payData);
                    $this->createdResponse(['redirect_url' => $ret, 'channel' => 'wxpay']);
                } catch (PayException $e) {
                    $this->errorResponse(10015, $e->getMessage());
                }
                break;
            case 'wx_pub':
                $config = C('sdk.wxpay');
                try {
                    $user = $this->user;
                    $connect = D('Connect')->where(['type' => 'weixin', 'uid' => $user['id']])->find();
                    if ($connect) {
                        $payData['openid'] = $connect['open_id'];
                        $ret = Charge::run($channel, $config, $payData);
                        $this->createdResponse(['payment' => $ret, 'channel' => 'wxpay']);
                    } else {
                        $this->errorResponse(30021);
                    }
                } catch (PayException $e) {
                    $this->errorResponse(10015, $e->getMessage());
                }
                break;
            case 'applepay':
                $dd = $this->getReceiptData('0B975BB9C85402EFA26EEE2F0D6093AB15451460AA2D7637CD2A32640F6BE059', true);
                break;
            default:
                $this->errorResponse(10014);
                break;
        }
    }

    /*
     * 发布话题
     */

    public function store() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
//        $this->checkNull($input, ['details', 'type']);
        if (!empty($input['pic'])) {
            $pics = explode(',', $input['pic']);
            $max = 9;
            if (count($pics) > $max) {
                $this->errorResponse(80001, "图片最多{$max}张");
            }
        }


        $postModel = D('Post');
        try {
            $id = $postModel->publish($this->user['id'], $input);
            $this->createdResponse(['message' => '发帖成功', 'id' => $id]);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 点赞
     */

    public function praise() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
        $id = $input['id'];
//        $user = $this->user;
        $postModel = D('Post');
        $post = D('Post')->find($id);
        try {
            $id = $postModel->praise($id, $this->user['id']);
//            $from = D('Users')->find($user['id']);
//            $to = D('Users')->find($post['user_id']);
            //D('Helper/Notification')->parise($from, $to);
            $this->createdResponse();
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    public function cancelPraise() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
        $id = $input['id'];
        $this->user['id'];
        D('PostZan')->where(['post_id' => $id, 'user_id' => $this->user['id']])->delete();
        D('Post')->where(['post_id' => $id])->setDec('zan_num', 1);
        $this->modifySuccessResponse();
//        $zan = D('PostZan')->where(['post_id' => $id, 'user_id' => $this->user['id']])->find();
//        if ($zan) {
//        } else {
//            $this->errorResponse(80003);
//        }
    }

    public function showDetail() {
        $input = $this->request();
        $id = $input['id'];
        $post = D('Post')->scope('valid')->where(['post_id' => $id])->find();
        if ($post) {
            ModelUtils::belongsTo($post, ['relation' => 'Account/Users', 'refKey' => 'user_id', 'foreignKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
            $post = transform('Post', 'index', $post);
            $is_favorite = D('UserFavorite')->where(['user_id' => $this->user['id'], 'to_user_id' => $post['author']['user_id']])->find();
            $post['is_favorite'] = 0;
            if ($is_favorite) {
                $post['is_favorite'] = 1;
            }
            /* 阅读数加1 */
            D('Post')->where(['post_id' => $id])->setInc('views', 1);
            $this->response($post);
        } else {
            $this->errorResponse(80004);
        }
    }

    public function praiseReply() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
        $id = $input['id'];
        $user = $this->user;
        $reply = D('PostReply')->find($id);
        $zan = D('ReplyZan')->where(['user_id' => $this->user['id'], 'reply_id' => $id])->find();
        if ($zan) {
            $this->errorResponse(80006);
        }
        $data = [
            'user_id' => $this->user['id'],
            'reply_id' => $id,
        ];
        $zanModel = D('ReplyZan');
        if ($zanModel->create($data)) {
            $zanModel->add();
            D('PostReply')->where(['reply_id' => $id])->setInc('zan_num', 1);
            $from = D('Users')->find($user['id']);
            $to = D('Users')->find($reply['user_id']);
            D('Helper/Notification')->parise($from, $to);
            $this->createdResponse();
        } else {
            $this->errorResponse(80000, $zanModel->getError());
        }
    }

    public function cancelReplyPraise() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
        $id = $input['id'];
        $zan = D('ReplyZan')->where(['user_id' => $this->user['id'], 'reply_id' => $id])->find();
        if (empty($zan)) {
            $this->errorResponse(80007);
        }
        D('ReplyZan')->where(['user_id' => $this->user['id'], 'reply_id' => $id])->delete();
        D('PostReply')->where(['reply_id' => $id])->setDec('zan_num', 1);
        $this->modifySuccessResponse();
    }

    /**
     * 回帖
     * contents 回复内容
     * id   帖子id
     * to_user_id 被评价者id
     * pid 被评论id
     */
    public function reply_bak() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
        $user = $this->user;
        $this->checkNull($input, ['id'], ['contents']);
        $id = $input['id'];
        $content = $input['contents'];
        $pid = $input['pid'] ? : 0;
        $rootReplyId = 0;
//        $post = D('Post')->find();
        $isPost = $pid == 0 ? true : false; //判断是否回复帖子

        if ($pid > 0) {//回复评价
            $parentReply = D('PostReply')->where(['reply_id' => $pid])->find();
//            if ($parentReply['user_id'] == $user['id']) {
//                $this->errorResponse(80005);
//            }
            $rootReplyId = $parentReply['pid'] > 0 ? $parentReply['root_reply_id'] : $parentReply['reply_id'];
        }

        $data = [
            'post_id' => $id,
            'user_id' => $user['id'],
            'zan_num' => 0,
            'contents' => $content,
            'audit' => 1,
            'pid' => $pid,
            'to_user_id' => $parentReply['user_id'] ? : 0,
            'root_reply_id' => $rootReplyId,
        ];
        $replyModel = D('PostReply');
        if ($replyModel->create($data)) {
            $replyModel->add();
            D('Post')->where(['post_id' => $id])->setInc('reply_num', 1);
            $from = D('Users')->find($user['id']);
            if ($parentReply) {
                $to = D('Users')->find($parentReply['user_id']);
            } else {
                $to = D('Users')->find($post['user_id']);
            }
            D('Helper/Notification')->reply($from, $to, $isPost);
            $this->createdResponse();
        } else {
            $this->errorResponse(80000, $replyModel->getError());
        }
    }

    /*
     * 回复帖子
     * id 帖子id
     * contents 内容
     * 发帖人post_user_id
     */

    public function reply() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
        $user = $this->user;
        $this->checkNull($input, ['id'], ['post_user_id'], ['contents']);
        $id = $input['id'];
        $to['user_id'] = $input['post_user_id'];
        $content = $input['contents'];
        $data = [
            'post_id' => $id,
            'user_id' => $user['id'],
            'zan_num' => 0,
            'contents' => $content,
            'audit' => 1,
            'pid' => $input['pid']? : ''
        ];
        $replyModel = D('PostReply');
        if ($replyModel->create($data)) {
            $replyModel->add();
            $this->Model->where(['post_id' => $id])->setInc('reply_num', 1);
            //D('Helper/Notification')->reply($this->userinfo, $to);
            $this->createdResponse();
        } else {
            $this->errorResponse(80000, $replyModel->getError());
        }
    }

    /*
     * 跟帖
     * id 帖子id
     * reply_user_id 被回复者id
     * reply_id 被评价内容id,
     * contents 内容
     * root_reply_id 一级回答者id
     */

    public function replyToReply() {
        // 禁言检查
        $this->forbid(2);
        $input = $this->request();
        $user = $this->user;
        // $this->checkNull($input, ['id'], ['reply_id'], ['to_user_id'], ['contents'], ['root_reply_id']);
        $id = $input['id'];
        $reply_id = $input['reply_id'];
        $root_reply_id = $input['root_reply_id'];
        $to['user_id'] = $input['reply_user_id'];
        $content = $input['contents'];
        $data = [
            'post_id' => $id,
            'user_id' => $user['id'],
            'zan_num' => 0,
            'contents' => $content,
            'audit' => 1,
            'pid' => $reply_id,
            'to_user_id' => $to['user_id'],
            'root_reply_id' => $root_reply_id,
        ];
        $replyModel = D('PostReply');
        if ($replyModel->create($data)) {
            $replyModel->add();
            $this->Model->where(['post_id' => $id])->setInc('reply_num', 1);
            // D('Helper/Notification')->reply($this->userinfo, $to);
            $this->createdResponse();
        } else {
            $this->errorResponse(80000, $replyModel->getError());
        }
    }

    public function getVideolList($id) {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);

        $where = [];
        $where['post_id'] = ['elt', $id];
        $where['type'] = 2;
        $count = D('Post')->scope('valid')->where($where)->count();
        $posts = D('Post')
                ->scope('valid')
                ->where($where)
                ->order('post_id desc')
                ->page($page, $perPage)
                ->select();
        ModelUtils::belongsTo($posts, ['foreignKey' => 'user_id', 'relation' => 'Account/Users', 'refKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
        $posts = transform('Post', 'index', $posts);
        $pagination = pagination($count, $perPage, $page);
        $this->response($posts, $pagination);
    }

    public function getReplies() {
        $input = $this->request();
        $id = $input['id'];
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 30);

        $where = ['post_id' => $id, 'root_reply_id' => 0];
        $count = D('PostReply')->scope('valid')->where($where)->count();
        $replies = D('PostReply')
                ->scope('valid')
                ->where($where)
                ->page($page, $perPage)
                ->order('create_time desc')
                ->select();
        ModelUtils::belongsTo($replies, ['relation' => 'Account/Users', 'fields' => ['user_id', 'nickname', 'face', 'sex'], 'refKey' => 'user_id', 'foreignKey' => 'user_id', 'name' => 'author']);
        $replies = transform('PostReply', 'index', $replies);

        if ($replies) {
            $replyIds = array_column($replies, 'reply_id');
            $subReplies = D('PostReply')
                    ->scope('valid')
                    ->where(['root_reply_id' => ['in', $replyIds]])
                    ->order('create_time desc')
                    ->select();
            ModelUtils::belongsTo($subReplies, ['relation' => 'Account/Users', 'fields' => ['user_id', 'nickname', 'face', 'sex'], 'refKey' => 'user_id', 'foreignKey' => 'user_id', 'name' => 'author']);
            ModelUtils::belongsTo($subReplies, ['relation' => 'Account/Users', 'fields' => ['user_id', 'nickname', 'face', 'sex'], 'refKey' => 'user_id', 'foreignKey' => 'to_user_id', 'name' => 'at']);
            $subReplies = transform('PostReply', 'sub', $subReplies);
            $subGroup = array_group($subReplies, 'root_reply_id');
            foreach ($replies as &$reply) {
                $reply['replies'] = $subGroup[$reply['reply_id']] ? : [];
            }
        }
        $pagination = pagination($count, $perPage, $page);
        $this->response($replies, $pagination);
    }

    public function getOneReply() {
        $input = $this->request();
        $id = $input['id'];
        $reply = D('PostReply')->find($id);
        ModelUtils::belongsTo($reply, ['relation' => 'Account/Users', 'refKey' => 'user_id', 'foreignKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
        $reply = transform('PostReply', 'sub', $reply);
        $this->response($reply);
    }

    public function getSubReplies() {
        $input = $this->request();
        $id = $input['id'];
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 200);
        $reply = D('PostReply')->find($id);
        ModelUtils::belongsTo($reply, ['relation' => 'Account/Users', 'refKey' => 'user_id', 'foreignKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
        $reply = transform('PostReply', 'sub', $reply);
        $count = D('PostReply')
                ->scope('valid')
                ->where(['root_reply_id' => $id])
                ->count();
        $subReplies = D('PostReply')
                ->scope('valid')
                ->where(['root_reply_id' => $id])
                ->page($page, $perPage)
                ->order('create_time desc')
                ->select();
        $pagination = pagination($count, $perPage, $page);
        ModelUtils::belongsTo($subReplies, ['relation' => 'Account/Users', 'refKey' => 'user_id', 'foreignKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
        ModelUtils::belongsTo($subReplies, ['relation' => 'Account/Users', 'refKey' => 'user_id', 'foreignKey' => 'to_user_id','fields' => $this->user_field, 'name' => 'at']);
        /* 删除二级评论的@ */
        foreach ($subReplies as &$subReply) {
            if ($subReply['pid'] == $id) {
                unset($subReply['at']);
            }
        }
        $subReplies = transform('PostReply', 'sub', $subReplies);
        $reply['replies'] = $subReplies;
        $this->response($reply, $pagination);
    }

    public function delReply() {
        $user = $this->user;
        $input = $this->request();
        $id = $input['id'];
        $reply = D('PostReply')->where(['user_id' => $user['id'], 'delete_time' => 0, 'reply_id' => $id])->find();
        if ($reply) {
            D('PostReply')->where(['reply_id' => $id])->setField('delete_time', time());
            D('Post')->where(['post_id' => $reply['post_id']])->setDec('reply_num', 1);
            $this->modifySuccessResponse();
        } else {
            $this->errorResponse(10000);
        }
    }

    public function getFavorites() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $postIds = D('PostFavorite')->where(['user_id' => $user['id']])->getField('post_id', true);
        if ($postIds) {
            $where = [];
            $where['post_id'] = ['in', $postIds];
            $count = D('Post')->scope('valid')->where($where)->count();
            $posts = D('Post')
                    ->scope('valid')
                    ->where($where)
                    ->order($order)
                    ->page($page, $perPage)
                    ->select();
            ModelUtils::belongsTo($posts, ['foreignKey' => 'user_id', 'relation' => 'Account/Users', 'refKey' => 'user_id','fields' => $this->user_field, 'name' => 'author']);
            $posts = transform('Post', 'index', $posts);
            $pagination = pagination($count, $perPage, $page);
            $this->response($posts, $pagination);
        } else {
            $pagination = pagination(0, $perPage, 1);
            $this->response([], $pagination);
        }
    }

    public function del() {
        $user = $this->user;
        $input = $this->request();
        $id = $input['id'];
        D('Post')->where(['post_id' => $id, 'user_id' => $user['id'], 'delete_time' => 0])->setField('delete_time', time());
        $this->modifySuccessResponse();
//        $post = D('Post')->where(['user_id' => $user['id'], 'post_id' => $id, 'delete_time' => 0])->find();
        if ($post) {
            D('Post')->where(['post_id' => $id])->setField('delete_time', time());
//            // 优先使用新版删除
//            $article = D('Article')->getByFromPostId($id);
//            if (empty($article)) {
//                // 删除相应的视频，注意，因为接口没有做频率限制，导致有很多手抖操作会有重复插入现象，所以这里只删除一条
//                // 有可能删除失败
//                $article = D('Article')->where(['video_url' => $post['video']])->find();
//            }
//            if ($article)
//                D('Article')->save(array_merge($article, ['is_show' => 0]));
//            D('Account/Users')->where(['user_id' => $userId])->setDec('posts_count');
//            D('PostTag')->where(['id' => $post['tag_id']])->setDec('count', 1);
            $this->modifySuccessResponse();
        } else {
            $this->errorResponse(10000);
        }
    }

    //屏蔽
    public function shield() {
        $input = $this->request();
        $to_user_id = $input['to_user_id'];
        $post_id = $input['post_id'];
        $user_id = $this->user['id'];
        $data = [
            'user_id' => $user_id,
            'to_user_id' => $to_user_id,
            'post_id' => $post_id,
            'add_time' => time()
        ];
        $shieldModel = D('shield_user_post');
        try {
            $shieldModel->add($data);
            $this->createdResponse();
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    //投诉帖子
    public function complaint() {
        $input = $this->request();
        $to_user_id = $input['to_user_id'];
        $user_id = $this->user['id'];
        $data = [
            'user_id' => $user_id,
            'to_user_id' => $to_user_id,
            'content' => $input['content'],
            'title' => $input['title'],
            'add_time' => time()
        ];
        $shieldModel = D('post_complaint');
        try {
            $shieldModel->add($data);
            $this->createdResponse();
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    public function getMyPost() {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $uid = $this->user['id'];
        if($input['user_id']){
            $uid = $input['user_id'];
        }
        $count = D('Post')->scope('valid')
//                ->cache('my_post_count'.$uid,60)
                ->where(['user_id' => $uid])->count();

        $posts = D('Post')
                ->scope('valid')
//                ->cache('my_post_'.$uid,60)
                ->where(['user_id' => $uid])
                ->page($page, $perPage)
                ->order('create_time desc')
                ->select();
        $data['posts'] = $posts;
        $data['user'] = D('users')->field($this->user_field)->find($uid);
        $pagination = pagination($count, $perPage, $page);
        $this->response($data, $pagination);
    }
    
    //删除缓存
     protected function delCache() {
         $uid = $this->user['id'];
        s('posts_count_'.$uid,null);    
        s('posts_'.$uid,null);    
        s('user_favorite_userinfo_'.$uid,null);    
    }

}
